<template>
  <div class="home">
    <Header></Header>
    <el-container>
      <el-aside width="160px">
        <el-menu
          :default-active="activeIndex"
          class="el-menu-vertical-demo"
          background-color="#f5f5f5"
          text-color="#909399"
          active-text-color="#f40"
          @select="handleSelect"
        >
          <el-menu-item index="1">
            <i class="el-icon-menu"></i>
            <span slot="title">个人资料</span>
          </el-menu-item>
          <el-menu-item index="2">
            <i class="el-icon-setting"></i>
            <span slot="title">安全设置</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <div class="main">
        <div class="box" v-if="index[0]">
          <div class="box-item">
            <span>用户ID：</span>
            <span>{{ user.userId }}</span>
          </div>
          <div class="box-item">
            <span>用户名：</span>
            <span>{{ user.username }}</span>
          </div>
          <div class="box-item">
            <span>昵称：</span>
            <span>{{ user.name }}</span>
          </div>
          <div class="box-item">
            <span>余额：</span>
            <span>￥{{ user.balance }}</span>
          </div>
          <div class="box-item">
            <span>类型：</span>
            <span>{{ user.type }}</span>
          </div>
          <div class="box-item">
            <span>邮箱：</span>
            <span>{{ user.email }}</span>
          </div>
          <div class="button" @click="changeInfo()">点击修改</div>
          <div class="change-box" v-if="changeIf">
            <el-form
              :model="forma"
              :rules="rulesa"
              ref="forma"
              label-width="100px"
              style="padding: 20px"
            >
              <el-form-item label="昵称" prop="name">
                <el-input v-model="forma.name" style="width: 300px"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="forma.email"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForma('forma')"
                >保存</el-button
                >
                <el-button @click="resetForm('forma')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="box" v-if="index[1]">
          <el-form
            ref="formb"
            :model="formb"
            :rules="rulesb"
            label-width="100px"
            class="formb"
          >
            <el-form-item label="原密码" prop="passwordpast">
              <el-input placeholder="请输入密码" v-model="formb.passwordpast"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="passwordnow">
              <el-input
                type="password"
                placeholder="密码至少为6位字符"
                v-model="formb.passwordnow"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPassword">
              <el-input
                type="password"
                placeholder="再次输入密码"
                v-model="formb.checkPassword"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <div style="text-align: center;">{{msg}}</div>
            <el-form-item>
              <el-button type="primary" @click="submitFormb('formb')">保存</el-button>
              <el-button @click="resetForm('formb')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-container>
  </div>
</template>

<script>
import Header from '@/components/Header.vue'

export default {
  components: {
    Header
  },
  data () {
    const checkPasswordPast = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入密码'))
      }
      setTimeout(() => {
        if (value !== this.user.password) {
          callback(new Error('密码错误'))
        } else {
          callback()
        }
      }, 100)
    }
    const checkCheckPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请再次输入密码'))
      }
      setTimeout(() => {
        if (value !== this.formb.passwordnow) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, 100)
    }
    const checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('请输入邮箱'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    return {
      activeIndex: '1',
      index: [true, false],
      user: {},
      changeIf: false,
      msg: '',
      forma: {
        name: '',
        email: ''
      },
      formb: {
        passwordpast: '',
        passwordnow: '',
        checkPassword: ''
      },
      rulesa: {
        name: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [{ validator: checkEmail, required: true, trigger: 'blur' }]
      },
      rulesb: {
        passwordpast: [
          { validator: checkPasswordPast, required: true, trigger: 'blur' }
        ],
        passwordnow: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 18, message: '密码6-18位', trigger: 'blur' }
        ],
        checkPassword: [
          { validator: checkCheckPassword, required: true, trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    const userInfo = JSON.parse(this.$cookie.get('userInfo'))
    this.user = userInfo
  },
  methods: {
    handleSelect (key) {
      for (let i = 0; i < this.index.length; i++) {
        this.index[i] = false
      }
      this.$set(this.index, key - 1, true)
      console.log(this.index)
    },
    submitForma (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const list = {
            userId: this.user.userId,
            balance: this.user.balance,
            type: this.user.type,
            email: this.forma.email,
            password: this.user.password,
            username: this.user.username,
            name: this.forma.name
          }
          this.$http.put(`users/${this.user.userId}`, list).then((res) => {
            console.log(res)
            if (res.status === 200) {
              alert('修改成功')
              this.user = res.data
              this.changeIf = false
              this.$cookie.set('userInfo', JSON.stringify(this.user))
              this.$router.go(0)
            } else {
              alert('失败')
            }
          }).catch((err) => {
            console.log(err.response)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitFormb (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const list = {
            userId: this.user.userId,
            balance: this.user.balance,
            type: this.user.type,
            email: this.user.email,
            password: this.formb.passwordnow,
            username: this.user.username,
            name: this.user.name
          }
          this.$http.put(`users/${this.user.userId}`, list).then((res) => {
            console.log(res)
            if (res.status === 200) {
              alert('修改成功')
              this.$cookie.remove('userInfo')
              this.$router.push('/Login')
              this.$http.post('loginOut').catch((err) => {
                console.log(err.response)
              })
            } else {
              alert('失败')
            }
          }).catch((err) => {
            console.log(err.response)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    changeInfo () {
      this.changeIf = true
    }
  }
}
</script>

<style lang="less" scoped>
.home {
  width: 100%;
  height: 80%;
  .el-container {
    width: 60%;
    height: 100%;
    margin: 20px auto;
    .el-menu {
      height: 80%;
    }
    .main {
      height: 80%;
      margin: 0 auto;
      padding: 10px;
      color: #909399;
      .box {
        width: 600px;
        margin-top: 20px;
        .box-item {
          width: 80%;
          height: 30px;
          margin: 0 auto;
          line-height: 30px;
          :nth-child(1) {
            display: inline-block;
            width: 80px;
          }
          :nth-child(2) {
            display: inline-block;
            width: 200px;
            color: rgb(80, 80, 80);
          }
          .change {
            margin-left: 50px;
            color: chocolate;
            cursor: pointer;
            &:hover {
              color: #f40;
            }
          }

        }
        .button {
          width: 100px;
          height: 50px;
          margin: 20px auto;
          background-color: rgb(214, 129, 98);
          border-radius: 20px;
          text-align: center;
          line-height: 50px;
          color: white;
        }
         /deep/ .el-button--primary {
                     background-color: #f40;
                     border-color: #f40;
                   }
        /deep/ .el-button--default {
          &:hover {
            background-color: rgb(252, 138, 97);
            border-color: rgb(252, 138, 97);
            color: white;
          }
          &:focus {
            background-color: white;
            color: black;
            border-color: rgb(200, 226, 253);;
          }
        }
        .box-item-last {
          width: 50px;
          margin: 0;
          padding-left: 340px;
        }
      }
    }
  }
}
</style>
